package com.zb.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 下载网络图片工具类
 * @Author WEN
 * @Date 2024/8/30 0030
 **/
@Log4j2
public class DownLoadNetworkFileUtil {

    /**
     * 下载网络文
     * @param networkImagePath 网络图片路径
     * @param saveFilePath 保存路径
     * @param visitPath 访问路径
     * @param fileName 文件名
     * @return
     */
    public static String downLoadNetworkImage(String networkImagePath, String saveFilePath, String visitPath, String fileName) {
        if (StringUtils.isBlank(networkImagePath)) {
            return "";
        }
        if (!saveFilePath.endsWith("/")) {
            saveFilePath = saveFilePath + "/";
        }
        if (!visitPath.endsWith("/")) {
            visitPath = visitPath + "/";
        }
        String filePath = visitPath + fileName;
        saveFilePath = saveFilePath + fileName;
        FileOutputStream fos = null;
        try {
            URL url = new URL(networkImagePath);
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();
            // 指定文件存储路径
            File file = new File(saveFilePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            // 构建图片文件输出流
            fos = new FileOutputStream(file);
            int len;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (IOException e) {
            log.error("图片文件下载失败，原因：" + e);
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {

                }
            }
        }
        return filePath;
    }

}
